package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.*;
import com.zzyl.entity.*;
import com.zzyl.enums.BalanceStatusEnum;
import com.zzyl.enums.CheckInStatusEnum;
import com.zzyl.mapper.*;
import com.zzyl.service.CheckInService;
import com.zzyl.service.ElderService;
import com.zzyl.vo.*;
import com.zzyl.vo.retreat.ElderVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CheckInServiceImpl implements CheckInService {

    final ElderService elderService;
    final CheckInMapper checkInMapper;
    final CheckInConfigMapper checkInConfigMapper;
    final ContractMapper contractMapper;

    final BedMapper bedMapper;
    final BalanceMapper balanceMapper;
    final ElderMapper elderMapper;
    final MemberMapper memberMapper;
    final MemberElderMapper memberElderMapper;


    /**
     * 分页查询
     *
     * @param elderName 老人姓名，模糊查询
     * @param idCardNo  身份证号，精确查询
     * @param pageNum   页码
     * @param pageSize  页面大小
     * @return 分页结果
     */
    @Override
    public PageBean<CheckInPageQueryVo> pageQuery(String elderName, String idCardNo, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        //老人姓名，模糊查询，这里进行预处理
        elderName = CharSequenceUtil.isBlank(elderName) ? null : "%" + elderName + "%";

        //这里只查询入住状态的
        Page<CheckInPageQueryVo> pageResult = checkInMapper.selectByPage(elderName, idCardNo, CheckInStatusEnum.PROGRESSING.getOrdinal());
        return PageBean.of(pageResult, CheckInPageQueryVo.class);
    }

    /**
     * 入住详情
     *
     * @param id 入住id
     * @return 入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        //老人信息
        ElderVo elderVo = elderService.selectByPrimaryKey(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elderVo, CheckInElderVo.class);
        checkInElderVo.setOneInchPhoto(elderVo.getImage());

        //入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.findCurrentConfigByElderId(checkIn.getElderId());

        //合同信息
        Contract contract = contractMapper.selectByContractNo(checkIn.getRemark());

        //封装响应信息
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(JSONUtil.toList(checkIn.getOtherApplyInfo(), ElderFamilyVo.class));
        checkInDetailVo.setCheckInConfigVo(BeanUtil.toBean(checkInConfig, CheckInConfigVo.class));
        checkInDetailVo.setCheckInContractVo(BeanUtil.toBean(contract, CheckInContractVo.class));
        return checkInDetailVo;
    }

    /**
     * 新增入住
     *
     * @param
     */
    @Override
    public void add(CheckInApplyDto checkInApplyDto) {

        //1.新增床位
        CheckInConfigDto configDto = checkInApplyDto.getCheckInConfigDto();
        Bed bed = Bed.builder()
                .bedStatus(1)
                .id(configDto.getBedId())
                .build();
        bedMapper.update(bed);
        bed = bedMapper.getById(configDto.getBedId());


        //2.新增老人信息
        CheckInElderDto elderDto = checkInApplyDto.getCheckInElderDto();

        Elder elder = BeanUtil.toBean(elderDto, Elder.class);
        elder.setImage(elderDto.getOneInchPhoto());
        elder.setStatus(0); //0入住中 1已退住 ElderStatusEnum
        elder.setBedId(bed.id);
        elder.setBedNumber(bed.getBedNumber());
        elderMapper.insert(elder); //主键自增返回

        //3.新增老人家属信息(会员)
        List<ElderFamilyDto> familyDtos = checkInApplyDto.getElderFamilyDtoList();
        familyDtos.forEach(familyDto -> {
            //添加会员
            Member member = Member.builder()
                    .phone(familyDto.getPhone())
                    .name(familyDto.getName())
                    .build();
            memberMapper.save(member);//最好先查询再保存

            //添加会员和老人关系
            MemberElder memberElder = MemberElder.builder()
                    .memberId(member.getId())
                    .elderId(elder.getId())
                    .remark(familyDto.getKinship())
                    .build();
            memberElderMapper.add(memberElder);
        });

        //4.新增入住信息
        String checkInCode = "RZ" + RandomUtil.randomNumbers(12);//生成入住编码

        CheckIn checkIn = new CheckIn();
        checkIn.setCheckInCode(checkInCode);
        checkIn.setTitle(elder.getName() + "的入住申请");
        checkIn.setElderId(elder.getId());
        checkIn.setCheckInTime(LocalDateTime.now());
        checkIn.setApplicat("管理员");//获取当前登录人的信息
        checkIn.setDeptNo("100001001000000");
        checkIn.setApplicatId(1671403256519078138L);
        checkIn.setStatus(0);//0入住中   1已退住
        checkIn.setOtherApplyInfo(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);

        //5.新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setElderId(elder.getId());
        checkInConfig.setBedNumber(bed.getBedNumber());
        checkInConfig.setCheckInCode(checkIn.getCheckInCode());
        String remark = checkInApplyDto.getCheckInConfigDto().getFloorId()
                + ":" + checkInApplyDto.getCheckInConfigDto().getRoomId()
                + ":" + checkInApplyDto.getCheckInConfigDto().getBedId()
                + ":" + checkInApplyDto.getCheckInConfigDto().getFloorName()
                + ":" + checkInApplyDto.getCheckInConfigDto().getCode();
        checkInConfig.setRemark(remark);
        checkInConfigMapper.insert(checkInConfig);

        //6.新增合同，如果入住开始时间小于当前时间，则合同状态设为生效中，否则为待生效
        String contractNo = "HT" + RandomUtil.randomNumbers(12);//生成合同编码

        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setContractNo(contractNo);
        contract.setCheckInNo(checkInCode);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStatus(1);//合同状态
        contract.setStartTime(configDto.getCheckInStartTime());
        contract.setEndTime(configDto.getCheckInEndTime());
        contractMapper.insert(contract);

        //7.新增或更新余额信息
        Balance balance = new Balance();
        balance.setElderId(elder.getId());
        balance.setElderName(elder.getName());
        balance.setBedNo(elder.getBedNumber());
        balance.setDepositAmount(checkInConfig.getDepositAmount());
        balance.setPrepaidBalance(new BigDecimal(0));
        balance.setArrearsAmount(new BigDecimal(0));
        balance.setStatus(BalanceStatusEnum.NORMAL.getOrdinal());

        Balance dbBalance = balanceMapper.selectByElderId(elder.getId());
        if (ObjectUtil.isNotEmpty(dbBalance)) {
            balance.setId(dbBalance.getId());
            balanceMapper.updateByPrimaryKeySelective(balance);
        } else {
            balanceMapper.insert(balance);
        }

        //8.新增首月账单，生成首月账单






        //9.生成护理任务




    }


}
